Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example, Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

题目大意:顺时针构造一个n维方阵,元素从1-n*n

题目难度:Medium

/**
 * Created by gzdaijie on 16/5/26
 */
public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] result = new int[n][n];

        int dir = 0;
        int k = 0;
        int x = 0, y = 0;
        int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        while (k++ < n * n) {
            result[x][y] = k;
            switch (dir) {
                case 0:
                    if (y < n - 1 && result[x][y + 1] == 0) y++;
                    else {
                        dir = (dir + 1) % 4;
                        x++;
                    }
                    break;
                case 1:
                    if (x < n - 1 && result[x + 1][y] == 0) x++;
                    else {
                        dir = (dir + 1) % 4;
                        y--;
                    }
                    break;
                case 2:
                    if (y > 0 && result[x][y - 1] == 0) y--;
                    else {
                        dir = (dir + 1) % 4;
                        x--;
                    }
                    break;
                case 3:
                    if (x > 0 && result[x - 1][y] == 0) x--;
                    else {
                        dir = (dir + 1) % 4;
                        y++;
                    }
                    break;
            }
        }
        return result;
    }
}
gzdaijie            updated 2016-05-26 21:34:18

results matching ""

    No results matching ""